//
//  PFBLableImageView.m
//  TestPresen
//
//  Created by Juvid on 16/8/11.
//  Copyright © 2016年 Juvid. All rights reserved.
//

#import "PFBLableImageView.h"
#import "UIView+JuLayGroup.h"
#import "UIView+StringFrame.h"
@implementation PFBLableImageView
@synthesize titleLable,imageView;
-(instancetype)init{
    self=[super init];
    if (self) {
        [self initView];
    }
    return self;
}
-(void)awakeFromNib{
    [self initView];
}
-(void)initView{
    _contentEdgeInsets=UIEdgeInsetsMake(0, 0, 0, 0);
    _HSpace=2;
    titleLable=[[UILabel alloc]init];
    [self addSubview:titleLable];
    titleLable.juEdge(_contentEdgeInsets);
}
-(void)setContentEdgeInsets:(UIEdgeInsets)contentEdgeInsets{
    _contentEdgeInsets=contentEdgeInsets;
    [self setImageAlignment:_imageAlignment];
}
-(void)setHSpace:(CGFloat)HSpace{
    _HSpace=HSpace;
    [self setImageAlignment:_imageAlignment];
}
-(void)setImageAlignment:(PFBImageAlignment)imageAlignment{
    _imageAlignment=imageAlignment;
    if (imageAlignment==PFBImageAlignmentLeft) {
        [self removeConstraint:imageView.ju_Trail];
        imageView.juLead.equal(_contentEdgeInsets.left);
        titleLable.juLeaSpace.toView(imageView).equal(_HSpace);
    }else if(imageAlignment==PFBImageAlignmentRight){
        [self removeConstraint:imageView.ju_Lead];
        imageView.juTrail.equal(_contentEdgeInsets.right);
        titleLable.juTraSpace.toView(imageView).equal(_HSpace);
    }else{
        titleLable.juLead.equal(_contentEdgeInsets.left);
        titleLable.juTrail.equal(_contentEdgeInsets.right);
    }
    [self setAutoWidth];
}
-(void)setAutoWidth{
    NSLayoutConstraint *widthCons=nil;
    for (NSLayoutConstraint *cons in self.constraints) {
        if (cons.firstAttribute==NSLayoutAttributeWidth) {
            widthCons=cons;
        }
    }
    if (!widthCons) {
        CGFloat lableW=[titleLable boundingWidth:MAXFLOAT];
        self.juWidth.priority(750).equal(_contentEdgeInsets.left+_contentEdgeInsets.right+_HSpace+imageView.ju_Width.constant+lableW);
    }
}
-(void)setImageString:(NSString *)imageString{
    UIImage *image=[UIImage imageNamed:imageString];
    if (!imageView) {
        imageView=[[UIImageView alloc]init];
        [self addSubview:imageView];
        imageView.juCenterY.equal(0);
        imageView.juLead.equal(_contentEdgeInsets.left);
    }
    if (image) {
        CGFloat mulit=image.size.height>self.ju_Height.constant?self.ju_Height.constant/image.size.height:1;
        CGSize size=CGSizeMake(image.size.width*mulit, image.size.height*mulit);
        imageView.juSize(size);
        imageView.image=image;
    }
    if (_imageAlignment!=PFBImageAlignmentRight) {
        self.imageAlignment=PFBImageAlignmentLeft;
    }
}
@end
